<template>
  <div class="forum-container">
    <!-- 搜索和操作区 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20" align="middle">
        <el-col :span="16">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索帖子标题或内容" 
            clearable
            size="large"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button 
            type="primary" 
            size="large" 
            @click="showPostDialog = true"
            class="publish-btn"
          >
            <el-icon class="el-icon--left"><EditPen /></el-icon> 发布新帖
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="post-list-card" shadow="never">
      <el-table 
        :data="filteredPosts" 
        style="width: 100%"
        :header-cell-style="{background: '#f8fafc', color: '#64748b'}"
      >
        <el-table-column 
          prop="title" 
          label="帖子标题" 
          min-width="400"
        >
          <template #default="scope">
            <span 
              class="post-title clickable" 
              @click="handleViewPost(scope.row)"
            >
              <span class="title-text">{{ scope.row.title }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="author" 
          label="作者" 
          width="140"
          align="center"
        >
          <template #default="scope">
            <div class="author-cell">
              <el-avatar :size="30" :src=scope.row.avatar />
              <span class="author-name">{{ scope.row.userNum }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="publishTime" 
          label="发布时间" 
          width="160"
          align="center"
        ><template #default="scope">
            <span class="count-number">{{ scope.row.createdAt }}</span>
          </template></el-table-column>
        <el-table-column 
          prop="replyCount" 
          label="回复数" 
          width="100"
          align="center"
        >
          <template #default="scope">
            <span class="count-number">{{ scope.row.replyCount }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="viewCount" 
          label="浏览量" 
          width="100"
          align="center"
        >
          <template #default="scope">
            <span class="count-number">{{ scope.row.viewCount }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="180"
          align="center"
        >
          <template #default="scope">
            <el-button 
              size="small" 
              type="text" 
              @click="handleViewPost(scope.row.id)"
              class="action-btn"
            >
              查看详情
            </el-button>
            <el-button 
              size="small" 
              type="text" 
              @click="handleDeletePost(scope.row.id)"
              class="action-btn"
              v-if="isAuthor(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发布帖子对话框 -->
    <el-dialog 
      title="发布新帖" 
      v-model="showPostDialog" 
      width="700px"
      class="post-dialog"
    >
      <el-form :model="newPost" :rules="postRules" ref="postFormRef" label-position="top">
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="newPost.title" 
            placeholder="请输入帖子标题"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="newPost.content" 
            type="textarea" 
            :rows="8" 
            placeholder="请输入帖子内容"
            resize="none"
            show-word-limit
            maxlength="2000"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPostDialog = false" size="large">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmPublish" 
          size="large"
          class="confirm-btn"
        >
          立即发布
        </el-button>
      </template>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog 
      title="帖子详情" 
      v-model="postDetailVisible" 
      width="800px"
      class="post-detail-dialog"
    >
      <!-- 帖子内容区域 -->
      <div class="post-detail" v-if="currentPost">
        <h2 class="post-title">{{ currentPost.title }}</h2>
        
        <div class="post-meta">
          <div class="author-info">
            <el-avatar :size="36" :src=currentPost.avatar />
            <span class="author-name">{{ currentPost.author }}</span>
          </div>
          <div class="post-stats">
            <span class="stat-item">
              <el-icon><Clock /></el-icon>
              {{ currentPost.createdAt }}
            </span>
            <span class="stat-item">
              <el-icon><View /></el-icon>
              {{ currentPost.viewCount }} 浏览
            </span>
            <span class="stat-item">
              <el-icon><Message /></el-icon>
              {{ currentPost.replyCount }} 回复
            </span>
          </div>
        </div>
        
        <el-divider />
        
        <div class="post-content">
          {{ currentPost.content }}
        </div>
      </div>
      
      <el-divider content-position="left">评论 ({{ comments.length }})</el-divider>
      
      <!-- 评论输入区域 -->
      <el-form :model="newComment" :rules="commentRules" ref="commentFormRef" class="comment-form">
        <el-form-item prop="content">
          <el-input 
            v-model="newComment.content" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入评论内容"
            resize="none"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitComment" class="submit-comment">发表评论</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-if="comments.length > 0">
          <div v-for="(comment, index) in comments" :key="index" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :size="40" :src= comment.avatar />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span>{{ comment.userNum}}</span>
                <span class="comment-time">{{ comment.createdAt }}</span>
                <el-button 
                  size="mini" 
                  type="text" 
                  @click="handleDeleteComment(comment.id)"
                  v-if="isCommentAuthor(comment)"
                >
                  删除
                </el-button>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
            </div>
          </div>
        </div>
        <div v-else class="no-comments">暂无评论，快来发表第一条评论吧~</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
// 1. 导入依赖（组件、API、Store、工具等）
import { ref, reactive, onMounted } from 'vue'
import { Search, EditPen, Clock, Message as MessageIcon, View } from '@element-plus/icons-vue'
// 导入接口函数
import { 
  addPost, 
  getAllPosts, 
  deletePost, 
  addComment, 
  getComments, 
  deleteComment
} from '../../../../api/user-forum/user-forum.js'
// 导入 Pinia Store（若使用 Pinia，原代码 useLoginStore 符合 Pinia 语法）
import { useLoginStore } from '../../../../stores/index.js'
import { ElMessage} from 'element-plus'


const loginStore = useLoginStore()
// 基础状态
const searchKeyword = ref('')
const showPostDialog = ref(false)
const postDetailVisible = ref(false)

// 表单相关（帖子发布、评论提交）
const newPost = reactive({ userNum: loginStore.user.number , title: '', content: '' })
const newComment = reactive({ content: '' })
const currentPost = ref(null)
const comments = ref([])
const filteredPosts = ref([])

// 表单验证规则（替代原 postRules/commentRules）
const postRules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})
const commentRules = ref({
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }]
})


// 表单引用（用于验证）
const postFormRef = ref(null)
const commentFormRef = ref(null)

// 4. 定义核心方法（替代原 methods 选项）
/**
 * 搜索帖子
 */
const handleSearch = () => {
  fetchPosts()
}

/**
 * @param {object} post - 帖子数据
 */
const handleViewPost = async (post) => {
  try {
    currentPost.value = filteredPosts.value[post-1]
    console.log('currentPost.value',currentPost);
    postDetailVisible.value = true
    fetchComments( currentPost.value.id )
  } catch (error) {
    ElMessage.error('获取帖子详情失败')
    console.error(error)
  }
}

/**
 * 确认发布帖子（表单验证 + 接口提交）
 */
const confirmPublish = async () => {
  // 表单验证（通过 ref 访问表单实例）
  const postForm = postFormRef.value
  if (!postForm) return

  try {
    await postForm.validate() // Composition API 中表单验证支持 Promise 语法
    const postData = {
      ...newPost,
    }
    await addPost(postData)
    ElMessage.success('帖子发布成功')
  } catch (error) {
    // 验证失败或接口报错均进入此处
    if (error.name !== 'ValidateError') { // 排除表单验证失败的错误提示
      ElMessage.error('发布失败，请重试')
      console.error(error)
    }
  }
}

/**
 * 提交评论
 */
const submitComment = async () => {
  const commentForm = commentFormRef.value
  if (!commentForm || !currentPost.value) return

  try {
    await commentForm.validate()
    const commentData = {
      postId: currentPost.value.id,
      content: newComment.content,
      userNum: loginStore.user.number
    }
    await addComment(commentData)
    ElMessage.success('评论成功')
    
  } catch (error) {
    if (error.name !== 'ValidateError') {
      ElMessage.error('评论失败，请重试')
      console.error(error)
    }
  }
}

/**
 * 拉取帖子列表（支持搜索）
 */
const fetchPosts = async () => {
  try {
    const response = await getAllPosts()
    filteredPosts.value = response
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
    console.error(error)
  }
}

/**
 * 拉取指定帖子的评论
 * @param {number} postId - 帖子 ID
 */
const fetchComments = async (postId) => {
  try {
      console.log('postId',postId);
    comments.value = await getComments(postId)
  } catch (error) {
    ElMessage.error('获取评论失败')
    console.error(error)
  }
}

/**
 * 删除帖子（确认框 + 接口提交）
 * @param {number} postId - 帖子 ID
 */
const handleDeletePost = async (postId) => {
  try {
    // 确认后执行删除
    await deletePost(postId)
    ElMessage.success('删除成功')
    await fetchPosts()
  } catch (error) {
    // 取消确认时 error 为 "cancel"，不提示错误
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

/**
 * 删除评论（确认框 + 接口提交）
 * @param {number} commentId - 评论 ID
 */
const handleDeleteComment = async (commentId) => {
  try {
      console.log(commentId);
    await deleteComment(commentId)
    ElMessage.success('删除成功')
    
    if (currentPost.value) {
      await fetchComments(currentPost.value.id)
      // 更新回复数（防止负数）
      if (currentPost.value.replyCount > 0) {
        currentPost.value.replyCount--
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

/**
 * 判断当前用户是否为帖子作者
 * @param {object} post - 帖子数据
 * @returns {boolean} 是否为作者
 */
const isAuthor = (post) => {
  return post.userNum === loginStore.user.number
}

/**
 * 判断当前用户是否为评论作者
 * @param {object} comment - 评论数据
 * @returns {boolean} 是否为作者
 */
const isCommentAuthor = (comment) => {
  return comment.userNum === loginStore.user.number
}

// 5. 生命周期钩子（替代原 mounted 选项）
onMounted(() => {
  // 组件挂载后拉取帖子列表
  console.log("loginStore",loginStore.user.number);
  fetchPosts()
})

</script>

<style scoped>
.forum-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.publish-btn {
  width: 100%;
}

.post-title {
  text-decoration: none;
  color: #333;
  cursor: pointer;
}

.title-text {
  margin-right: 8px;
}

.author-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-weight: 500;
}

.count-number {
  font-weight: 600;
  color: #1890ff;
}

.action-btn {
  color: #1890ff;
}

/* 详情对话框样式 */
.post-detail-dialog {
  .post-title {
    margin-bottom: 16px;
    color: #1f2937;
  }
  
  .post-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .author-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .post-stats {
    display: flex;
    gap: 16px;
    color: #64748b;
  }
  
  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .post-content {
    line-height: 1.8;
    color: #374151;
    margin-bottom: 16px;
  }
}

.comment-form {
  margin-bottom: 20px;
}

.submit-comment {
  margin-top: 8px;
}

.comments-list {
  max-height: 400px;
  overflow-y: auto;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f1f5f9;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #1f2937;
}

.comment-time {
  font-size: 12px;
  color: #64748b;
}

.comment-text {
  margin: 0;
  line-height: 1.6;
  color: #374151;
}

.no-comments {
  text-align: center;
  color: #64748b;
  padding: 40px 0;
}
</style>